const { Sequelize } = require('sequelize');
const path = require('path');
const fs = require('fs');

// 1. 加载环境变量
const env = process.env.NODE_ENV || 'development';
const envFile = path.join(__dirname, 'env', `${env}.env`);
if (!fs.existsSync(envFile)) throw new Error(`Missing env file: ${envFile}`);
require('dotenv').config({ path: envFile });

// 2. 创建 Sequelize 实例
const sequelize = new Sequelize({
  dialect: 'mysql',
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  port: parseInt(process.env.DB_PORT || '3306'),
  // logging:false,
  logging: process.env.NODE_ENV === 'development'
    ? console.log  // 开发环境完整日志
    : (sql, timing) => {
      // 生产环境只记录错误和慢查询
      if (timing > 1000 || sql.includes('ERROR')) {
        console.error(`[SQL] ${sql} (${timing}ms)`);
        // 可以接入Sentry等监控系统
        // Sentry.captureMessage(`Slow SQL: ${sql}`);
      }
    },
  benchmark: true // 启用执行时间统计
});

// 3. 测试连接
sequelize.authenticate()
  .then(() => console.log('✅ 数据库连接成功'))
  .catch(err => console.error('❌ 连接失败:', err));

module.exports = sequelize; // 仅导出实例